#pragma once
#include <string>
#include <memory>
#include <map>
#include <functional>
#include <mutex>
#include <vector>
#include "framework/service_interface.h"
namespace cpp_backend
{
    namespace framework
    {
        /**
         * @brief 服务工厂(单例模式 + 工厂模式)
         * 负责服务的注册、创建和管理
         */
        class ServiceFactory
        {
        public:
            using ServiceCreator = std::function<std::shared_ptr<IService>()>;
            /**
             * @brief 获取单例
             */
            static ServiceFactory &GetInstance()
            {
                static ServiceFactory instance;
                return instance;
            }
            /**
             * @brief 注册服务
             */
            bool RegisterService(const std::string &service_name, ServiceCreator creator)
            {
                std::lock_guard<std::mutex> lock(mutex_);
                if (creators_.find(service_name) != creators_.end())
                {
                    LOG_ERROR << "Service " << service_name << " already exists";
                    return false;
                }
                creators_[service_name] = creator;
                LOG_INFO << "Register service " << service_name;
                return true;
            }
            /**
             * @brief 取消注册服务
             * @param service_name 服务名
             * @return 是否成功
             */
            bool UnregisterService(const std::string &service_name)
            {
                std::lock_guard<std::mutex> lock(mutex_);
                if (creators_.find(service_name) == creators_.end())
                {
                    LOG_ERROR << "Service " << service_name << " not exists";
                    return false;
                }
                auto it = creators_.erase(service_name);
                if (it > 0)
                {
                    LOG_INFO << "Unregister service " << service_name;
                    return true;
                }
                return false;
            }

            /**
             * @brief 创建服务
             * @param service_name 服务名
             * @return 服务实例
             */
            std::shared_ptr<IService> CreateService(const std::string &service_name)
            {
                std::lock_guard<std::mutex> lock(mutex_);
                auto it = creators_.find(service_name);
                if (it == creators_.end())
                {
                    LOG_ERROR << "Service " << service_name << " not exists";
                    return nullptr;
                }
                return it->second();
            }
            /**
             * @brief 创建并初始化服务
             * @param service_name 服务名
             * @return 服务实例指针，失败返回nullptr
             */
            IServicePtr CreateAndInitService(const std::string &service_name)
            {
                auto service = CreateService(service_name);
                if (!service)
                {
                    return nullptr;
                }
                if (!service->Initialize())
                {
                    return nullptr;
                }
                return service;
            }
            /**
             * @brief 获取所有已注册的服务名称
             *
             * @return 服务名称列表
             */
            std::vector<std::string> GetRegisteredServices() const
            {
                std::lock_guard<std::mutex> lock(mutex_);

                std::vector<std::string> services;
                services.reserve(creators_.size());

                for (const auto &pair : creators_)
                {
                    services.push_back(pair.first);
                }

                return services;
            }

            /**
             * @brief 检查服务是否已注册
             *
             * @param service_name 服务名称
             * @return 是否已注册
             */
            bool IsServiceRegistered(const std::string &service_name) const
            {
                std::lock_guard<std::mutex> lock(mutex_);
                return creators_.find(service_name) != creators_.end();
            }

            /**
             * @brief 获取已注册服务数量
             */
            size_t GetServiceCount() const
            {
                std::lock_guard<std::mutex> lock(mutex_);
                return creators_.size();
            }

            /**
             * @brief 清空所有注册的服务
             */
            void Clear()
            {
                std::lock_guard<std::mutex> lock(mutex_);
                creators_.clear();
            }

        private:
            ServiceFactory() = default;
            ~ServiceFactory() = default;
            ServiceFactory(const ServiceFactory &) = delete;
            ServiceFactory &operator=(const ServiceFactory &) = delete;
            mutable std::mutex mutex_;
            std::map<std::string, ServiceCreator> creators_;
        };
        /**
         * @brief 服务自动注册辅助类
         * 利用全局变量初始化机制，在main函数执行之前自动注册服务
         *
         */
        class ServiceRegister
        {
        public:
            ServiceRegister(const std::string &service_name, ServiceFactory::ServiceCreator creator)
            {
                ServiceFactory::GetInstance().RegisterService(service_name, creator);
            }
        };
    }
}
// 定义服务注册函数（可供显式调用）
#define DECLARE_SERVICE_REGISTRAR(ServiceClass, ServiceName)                                                                      \
    void _register_##ServiceClass();                                                                                              \
    inline void _register_##ServiceClass()                                                                                        \
    {                                                                                                                             \
        ::cpp_backend::framework::ServiceFactory::GetInstance().RegisterService(                                                  \
            ServiceName,                                                                                                          \
            []() -> ::cpp_backend::framework::IServicePtr { return std::make_shared<::cpp_backend::services::ServiceClass>(); }); \
    }

// 主注册宏
#ifdef MANUAL_SERVICE_REGISTRATION
// 手动注册模式：只声明函数，不自动执行
#define REGISTER_SERVICE(ServiceClass, ServiceName) \
    DECLARE_SERVICE_REGISTRAR(ServiceClass, ServiceName)
#else
// 自动注册模式：声明函数 + 通过静态变量自动执行
#define REGISTER_SERVICE(ServiceClass, ServiceName)                                                                                   \
    DECLARE_SERVICE_REGISTRAR(ServiceClass, ServiceName)                                                                              \
    namespace                                                                                                                         \
    {                                                                                                                                 \
        static ::cpp_backend::framework::ServiceRegister                                                                              \
            _service_registrar_##ServiceClass(                                                                                        \
                ServiceName,                                                                                                          \
                []() -> ::cpp_backend::framework::IServicePtr { return std::make_shared<::cpp_backend::services::ServiceClass>(); }); \
    }
#endif

// 调用已声明的注册函数
#define INVOKE_SERVICE_REGISTRATION(ServiceClass) \
    do                                            \
    {                                             \
        extern void _register_##ServiceClass();   \
        _register_##ServiceClass();               \
    } while (0)
